﻿using System.Text;

namespace AllServer.Core.SqlSugar;

/// <summary>
/// sqlsugar 扩展
/// </summary>
public static class SqlSugarExtensions
{
    #region utils
    /// <summary>
    /// 创建实体类
    /// </summary>
    /// <param name="services"></param>
    /// <param name="config"></param>
    public static void CreateEntities(this IServiceCollection services, GenSqlSuarModelConfig config)
    {
        Task.Run(() =>
        {
            var db = DbContext.Instance.GetConnection(config.DbConfigId);

            foreach (var item in db.DbMaintenance.GetTableInfoList())
            {
                string entityName = StrFirstUpper(item.Name);/*实体名大写*/
                db.MappingTables.Add(entityName, item.Name);
                foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name))
                {
                    db.MappingColumns.Add(StrFirstUpper(col.DbColumnName) /*类的属性大写*/, col.DbColumnName, entityName);
                }
            }

            db.DbFirst
                .Where(w => config.Tables == null || config.Tables.Count == 0 ? true : config.Tables.Contains(w))
                .SettingClassTemplate(old =>
                {
                    return @"{using}
namespace {Namespace};
{ClassDescription}{SugarTable}
    public partial class {ClassName}
    {
{PropertyName}
    }
";
                })
                .SettingNamespaceTemplate(old => { return old; })//命名空间 
                .SettingPropertyDescriptionTemplate(old => //备注
                {
                    return @"        /// <summary>
        /// {PropertyDescription}
        /// </summary>";
                })
                .SettingPropertyTemplate((columns, temp, type) =>
                {
                    temp = "           {SugarColumn}\r\n        public {PropertyType} {PropertyName} {get;set;}";

                    var columnattribute = "\r\n        [SugarColumn({0})]";
                    List<string> attributes = new List<string>();
                    if (columns.IsPrimarykey)
                        attributes.Add("IsPrimaryKey=true");
                    if (columns.IsIdentity)
                        attributes.Add("IsIdentity=true");
                    if (columns.IsJson || columns.DataType.ToLower() == "json")
                        attributes.Add("IsJson = true");

                    attributes.Add($"ColumnName=\"{columns.DbColumnName}\"");
                    if (attributes.Count == 0)
                    {
                        columnattribute = "";
                    }
                    return temp.Replace("{PropertyType}", type)
                                .Replace("{PropertyName}", StrFirstUpper(columns.DbColumnName))
                                .Replace("{SugarColumn}", string.Format(columnattribute, string.Join(",", attributes)));
                })//属性
                  //.SettingConstructorTemplate(old => { return old+"123"; })//构造函数
                  //.IsCreateDefaultValue()
                .IsCreateAttribute()
                .CreateClassFile(config.Path, config.NameSpace);
        });
    }

    /// <summary>
    /// 将字符串的第一个字符大写
    /// 由 _ 分割 将组合 每个单词首字符大写
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    private static string StrFirstUpper(string str)
    {
        if (string.IsNullOrEmpty(str)) return str;
        StringBuilder result = new StringBuilder();
        foreach (var item in str.Split('_'))
        {
            if (item.Length > 1)
            {
                var first = item.Substring(0, 1).ToUpper();
                var last = item.Substring(1);
                result.Append(first);
                result.Append(last);
            }
            else
            {
                result.Append(item);
            }
        }
        return result.ToString();
    }
    #endregion
}